// =========================================== 自己实现 grep
pub mod t0_0 {
    use std::env;
    use std::error::Error;
    use std::fs;
    use std::process;

    pub struct Config {
        pub query: String,
        pub filename: String,
    }

    impl Config {
        pub fn new(mut args: std::env::Args) -> Result<Config, &'static str> {
            args.next();

            let query = match args.next() {
                Some(arg) => arg,
                None => return Err("Didn't get a query string"),
            };

            let filename = match args.next() {
                Some(arg) => arg,
                None => return Err("Didn't get a file name"),
            };

            let case_sensitive = env::var("CASE_INSENSITIVE").is_err();

            Ok(Config { query, filename })
        }
    }

    pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
        contents.lines().filter(|line| line.contains(query)).collect()
    }

    // ----------------------------- search string
    pub fn file_search(config: Config) -> Result<(), Box<dyn Error>> {
        let contents = fs::read_to_string(config.filename)?;

        for line in search(&config.query, &contents) {
            println!("{}", line);
        }
        Ok(())
    }

    //  命令行
    pub fn run_search() {
        let args: Vec<String> = env::args().collect();
        println!("{:?}", args);

        let config = Config::new(env::args()).unwrap_or_else(|err| {
            println!("Problem parsing arguments: {}", err);
            process::exit(1);
        });

        println!("Searching for {}", config.query);
        println!("In file {}", config.filename);

        if let Err(e) = file_search(config) {
            println!("Application error: {}", e);
            process::exit(1);
        }
    }

    // ------------------------------------- test
    #[cfg(test)]
    pub mod tests {
        //use crate::test::te_grep::search;
        use super::search;
        #[test]
        fn one_result() {
            let query = "duct";
            let contents = "\
Rust:safe, fast, 
productive. Pick three.";

            assert_eq!(vec!["safe, fast, productive."], search(query, contents))
        }
    }
}

// =========================================== 猜数字游戏
pub mod t0_1 {
    use rand::Rng;
    use std::cmp::Ordering;
    use std::io;

    pub fn guess() {
        println!("Guess the number!");

        let secret_number = rand::thread_rng().gen_range(1..101);
        //println!("The secret number is: {secret_number}");

        loop {
            println!("Please input your guess.");
            let mut guess = String::new();
            io::stdin().read_line(&mut guess).expect("Failed to read line");

            let guess: u32 = match guess.trim().parse() {
                Ok(num) => num,
                Err(_) => continue,
            };

            println!("You guessed: {guess}");

            match guess.cmp(&secret_number) {
                Ordering::Less => println!("Too small!"),
                Ordering::Greater => println!("Too big!"),
                Ordering::Equal => {
                    println!("You win!");
                    break;
                }
            }
        }
    }
}
